import { Col, Form, Input, InputNumber, Row, Select, TreeSelect } from 'antd';
import { RuleNumberRange } from '../common/NumberRange';
import { useRequest } from 'umi';
import { getFlowOrgTreeByOrgIDService, loadMdicMap } from '@/services/BaseLayout';
import { getDeptPosTreeIcon, getLoadMapList, getPosIDs, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import '../common/styles.less';
import { RegularExpression } from '@/common/constVariable';
import { useState, useEffect } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { RuleManageAPI } from '../common/type';

const RuleInfoForm: React.FC<RuleManageAPI.IRuleInfoFormAPI> = ({ setDutyIdFun }) => {
  /**
   * 获取组织机构树接口
   * */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /**
   * 获取数据字典
   * */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`,
    // `${getTenantID()}${ILoadMapTypeAll.PURCHASE_SUPPLY}`,
    // `${getTenantID()}${ILoadMapTypeAll.PROCURE_NCFS}`,
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`,
  ];

  const { loadMapInfo, mapLoading } = getLoadMapList(loadMdicIds);

  /**
   * 数量的控制
   * */
  const [numControl, setNumControl] = useState({
    priceWeight: 0,
    techWeight: 0,
    busiWeight: 0,
  });

  /**
   * 处理树数据
   * */
  const filterCompanyAndDepartment = (treeData: any[]): any[] => {
    return treeData
      .map((node) => {
        if (node.textType === '0' || node.textType === '1') {
          return {
            ...node,
            title: (
              <div>
                {getDeptPosTreeIcon(String(node?.textType))}
                {node?.text}
              </div>
            ),
            searchtitle: node?.text,
            key: node?.id,
            value: node?.id,
            disabled: node.textType === '0',
            children: filterCompanyAndDepartment(node.children),
          };
        }
      })
      .filter(Boolean);
  };

  /**
   * 点击树结构
   * */
  const onTreeSelect = (selectedKeys: any, selectedNodes: any) => {
    /**
     * 向外层丢出
     * */
    setDutyIdFun({
      dep: selectedNodes?.id,
      com: selectedNodes?.attributes?.companyID,
    });
  };

  /**
   * 初始化请求组织机构
   * */
  useEffect(() => {
    let payload = {
      params: '0',
      flowType: '0',
      orgID: getPosIDs(),
    };
    getFlowOrgTreeRun(payload);
  }, []);

  return (
    <>
      <Row className={pageStyles['fromView-labelLength']}>
        <Col span={12}>
          <Form.Item
            name="ruleTitle"
            label="规则标题"
            rules={[
              {
                required: true,
                message: '请输入规则标题',
              },
            ]}
          >
            <Input placeholder="请输入规则标题" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="supplyWay" // 采购办法(0：月度计划 1：零星采购 2： 实验平台)
            label="采购办法"
            rules={[
              {
                required: true,
                message: '请选择采购办法',
              },
            ]}
          >
            <Select
              placeholder="请选择采购办法"
              options={[
                {
                  value: 0,
                  label: '月度计划',
                },
                {
                  value: 1,
                  label: '零星采购',
                },
                {
                  value: 2,
                  label: '实验平台',
                },
              ]}
            />
          </Form.Item>
        </Col>
        <Col span={24}>
          <Form.Item
            name="ruleInfo"
            label="规则介绍"
            rules={[
              {
                required: true,
                message: '请输入规则介绍',
              },
            ]}
          >
            <Input.TextArea placeholder="请输入规则介绍" maxLength={300} autoSize={{ minRows: 3, maxRows: 5 }} showCount />
          </Form.Item>
        </Col>

        <Col span={12}>
          <Form.Item
            name="supplyKind" // 采购类别(字典...职能类 科研类)
            label="采购类别"
            rules={[
              {
                required: true,
                message: '请选择采购类别',
              },
            ]}
          >
            <Select placeholder="请选择采购办法" loading={mapLoading}>
              {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]?.map((item: Record<string, any>) => {
                return (
                  <Select.Option key={item?.id} value={item?.id}>
                    {item?.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="supplyType" // (字典... 等于物料里的供货分类)
            label="采购类型"
            rules={[
              {
                required: true,
                message: '请选择采购类型',
              },
            ]}
          >
            <TreeSelect
              loading={mapLoading}
              placeholder={'请选择采购类型'}
              showSearch
              allowClear
              treeNodeFilterProp={'searchtitle'}
              treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}`]}
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="procureDraft" // 字典
            label="拟采方式"
            rules={[
              {
                required: true,
                message: '请选择拟采方式',
              },
            ]}
          >
            <TreeSelect
              loading={mapLoading}
              placeholder={'请选择拟采方式'}
              showSearch
              allowClear
              treeNodeFilterProp={'searchtitle'}
              treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]}
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="procureReal" // 字典
            label="可变更采购方式"
            rules={[
              {
                required: true,
                message: '请选择可变更采购方式',
              },
            ]}
          >
            <TreeSelect
              loading={mapLoading}
              placeholder={'请选择可变更采购方式'}
              showSearch
              allowClear
              treeNodeFilterProp={'searchtitle'}
              treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`]}
              fieldNames={{
                label: 'name',
                value: 'id',
                children: 'children',
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="ruleStyle"
            label="比较方式"
            rules={[
              {
                required: true,
                message: '请选择比较方式',
              },
            ]}
          >
            <Select
              placeholder="请选择比较方式"
              options={[
                {
                  value: 0,
                  label: '前开后开',
                },
                {
                  value: 1,
                  label: '前开后闭',
                },
                {
                  value: 2,
                  label: '前闭后开',
                },
                {
                  value: 3,
                  label: '前闭后闭',
                },
              ]}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <RuleNumberRange formname={'planPrice'} label={'预算费用（元）'} placeholder={'预算费用'} />
        </Col>
        <Col span={12}>
          <Form.Item
            name="supplierMinNum"
            label="邀请最少供应商数量"
            rules={[
              {
                required: true,
                message: '请输入邀请最少供应商数量',
              },
              {
                pattern: RegularExpression.integerNumber,
                message: '请输入正确的供应商数量',
              },
            ]}
          >
            <Input placeholder="请输入邀请最少供应商数量" />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="dutyDepartmentID"
            label="归口部门"
            rules={[
              {
                required: true,
                message: '请选择归口部门',
              },
            ]}
          >
            <TreeSelect
              loading={getFlowOrgTreeLoading}
              placeholder={'请选择归口部门'}
              showSearch
              allowClear
              treeNodeFilterProp={'searchtitle'}
              treeData={filterCompanyAndDepartment(getFlowOrgList)}
              onSelect={onTreeSelect}
              fieldNames={{
                label: 'text',
                value: 'id',
                children: 'children',
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name={'priceWeight'}
            label={'价格权重'}
            rules={[
              {
                required: true,
                message: '请填写价格权重',
              },
              {
                pattern: RegularExpression.integerNumber,
                message: '请填写正确的价格权重',
              },
            ]}
          >
            <InputNumber
              placeholder="价格权重+技术权重+商务权重=100%"
              addonAfter="%"
              min={numControl?.techWeight && numControl?.busiWeight ? 100 - numControl?.techWeight - numControl?.busiWeight : 0}
              max={100 - numControl?.techWeight - numControl?.busiWeight}
              onChange={(val: number | null) => {
                setNumControl({
                  ...numControl,
                  priceWeight: Number(val),
                });
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name={'techWeight'}
            label={'技术权重'}
            rules={[
              {
                required: true,
                message: '请填写技术权重',
              },
              {
                pattern: RegularExpression.integerNumber,
                message: '请填写正确的技术权重',
              },
            ]}
          >
            <InputNumber
              placeholder="价格权重+技术权重+商务权重=100%"
              addonAfter="%"
              min={numControl?.priceWeight && numControl?.busiWeight ? 100 - numControl?.priceWeight - numControl?.busiWeight : 0}
              max={100 - numControl?.priceWeight - numControl?.busiWeight}
              onChange={(val: number | null) => {
                setNumControl({
                  ...numControl,
                  techWeight: Number(val),
                });
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name={'busiWeight'}
            label={'商务权重'}
            rules={[
              {
                required: true,
                message: '请填写商务权重',
              },
              {
                pattern: RegularExpression.integerNumber,
                message: '请填写正确的商务权重',
              },
            ]}
          >
            <InputNumber
              placeholder="价格权重+技术权重+商务权重=100%"
              addonAfter="%"
              min={numControl?.priceWeight && numControl?.techWeight ? 100 - numControl?.priceWeight - numControl?.techWeight : 0}
              max={100 - numControl?.priceWeight - numControl?.techWeight}
              onChange={(val: number | null) => {
                setNumControl({
                  ...numControl,
                  busiWeight: Number(val),
                });
              }}
            />
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            name="ruleDayNum"
            label="澄清截至天数"
            rules={[
              {
                required: true,
                message: '请输入澄清截至天数',
              },
            ]}
          >
            <Input placeholder="请输入澄清截至天数" addonAfter="天" />
          </Form.Item>
        </Col>
      </Row>
    </>
  );
};
export { RuleInfoForm };
